<?php

require_once 'inc/facebook/facebook.php';
require_once 'core/uea-web-services-tools.php';
require_once 'core/auth.php';

$appapikey = '145156303e12d73a83026a292f99ea06';
$appsecret = '73085c7ff32cbfb25eed7d15d75df255';

define('FACEBOOK_APP_ID', $appapikey);
define('FACEBOOK_SECRET', $appsecret);

// create the application based on the key & secret
$facebook = new Facebook($appapikey, $appsecret);

# parse the OAuth information from the signed_request parameter
$signedRequest = parse_signed_request($_REQUEST["signed_request"], $appsecret);

# buffer everything to $html
$html = "";

#error_reporting(E_ALL ^ E_WARNING );

# is the user authenticated? i.e. viewing fb, but not logged into fb
if( isset($signedRequest["oauth_token"]) )
{
	$responseBody = null;

	# speak to ueaWolfie
	try
	{
		$responseBody = getPatronInformation( "access_token=".$signedRequest["oauth_token"],FACEBOOK_EXTERNAL_SYSTEM_ID, $forceCacheRefresh = true);
	}
	catch (Exception $e)
	{
		print_r($e);
	}

	# quick check for errors
	if( strpos ( $responseBody, "Error retrieving Patron System Key" ) )
	{
		$html.= "<p>There was an error retrieving your library borrower record. Please contact technical support to investigate this.</p>";
		return;
	}
	else
	{

        # perform the XSLT transformations
        try
        {
			$finalBorrowingResult = performXSLTTransform($responseBody, 'xsl/borrowing.xsl');
			$finalHoldingResult   = performXSLTTransform($responseBody, 'xsl/holdings.xsl');
			$finalFinesResult     = performXSLTTransform($responseBody, 'xsl/fines.xsl');
        }
        catch (Exception $xste)
        {
            $html .="XSTE exception = " + xste.getMessage();
        }

        if ($finalBorrowingResult == null || trim($finalBorrowingResult) == "")
		{
			$finalBorrowingHTML = "<p>You have no borrowed books at the moment.</p>";
		}
		else
		{
			$finalBorrowingHTML =
				"<h4>Current Loans</h4>".
				"<table class=\"libraryRecords\" border=\"0\" cellspacing=\"0\" cellpadding=\"1\" summary=\"This table contains a summary of your current library loans.\">" .
				"   <tr>" .
				"       <th scope=\"col\" width=\"35%\">Title</th>" .
				"       <th scope=\"col\" width=\"35%\">Author</th>" .
				"       <th scope=\"col\" width=\"15%\">Due Date</th>" .
				"       <th scope=\"col\" width=\"15%\">Fine (&pound;)</th>" .
				"   </tr>" .
				$finalBorrowingResult .
				"</table>";
		}

		if ($finalFinesResult == null || $finalFinesResult == "" )
		{
			$finalFinesHTML = "";
		}
		else
		{
			$finalFinesHTML =
				"<div id=\"libaryFines\">" .
				"<h4>Fines</h4>".
				$finalFinesResult.
				"</div>";
		}

		if ($finalHoldingResult == null || $finalHoldingResult == "")
		{
			$finalHoldingHTML = "<p>You do not have any library reservations at the moment.</p>";
		}
		else
		{
			$finalHoldingHTML =
				"<h4>Current Reservations</h4>".
				"<table class=\"libraryRecords\" border=\"0\" cellspacing=\"0\" cellpadding=\"1\" summary=\"This table contains a summary of your current library reservations.\">" .
				"   <tr>".
				"       <th scope=\"col\" width=\"50%\">Title</th>".
				"       <th scope=\"col\">Author</th>" .
				"       <th scope=\"col\">Request End Date</th>" .
				"   </tr>".
				$finalHoldingResult.
				"</table>";
        }
        $html .= $finalBorrowingHTML . $finalFinesHTML . $finalHoldingHTML;




	}
















        	#
			# process top 5 loan stuff
			#
			if( isset($_REQUEST["course_code"]))
			{
				try
				{
					$responseBody = getTop5Loans( "access_token=".$signedRequest["oauth_token"],FACEBOOK_EXTERNAL_SYSTEM_ID, $courseCode = $_REQUEST["course_code"] );
				}
				catch (Exception $e)
				{
					print_r($e);
				}

				// perform the XSLT transformations
				try
				{
					$top5Loans = performXSLTTransform($responseBody, 'xsl/top5loans.xsl');
				#	$finalHoldingResult   = performXSLTTransform($responseBody, 'xsl/holdings.xsl');
				#	$finalFinesResult     = performXSLTTransform($responseBody, 'xsl/fines.xsl');
				}
				catch (Exception $xste)
				{
					//xste.printStackTrace(System.err);
					$html .= "XSTE exception = " + xste.getMessage();
				}
				$top5Loans =
					"<h4>Top 5 Loans for ".$_REQUEST["course_code"]."</h4>" .
					"<table class=\"libraryRecords\" border=\"0\" cellspacing=\"0\" cellpadding=\"1\" summary=\"This table contains a summary of the top 5 loans for ".$_REQUEST["course_code"].".\">" .
					"   <tr>" .
					"       <th scope=\"col\">Rank</th>" .
					"       <th scope=\"col\" width=\"50%\">Title</th>" .
					"       <th scope=\"col\">Author</th>" .
					"   </tr>" .
					$top5Loans .
					"</table>";
				$html .= $top5Loans;
			}
			else
			{
				$html .= "<h4>Top 5 Loans For A Course</h4>";
			}
			if( isset($signedRequest["oauth_token"]) )
			{
				$html .= '
					<form name="top5OnCourse" id="top5OnCourse" method="post">
				    	<label for="course_code">Please enter a course code:</label>
						<input type="text" name="course_code" value="" />
						<input name="formSubmit" type="submit" value="Search">
					</form>';
			}


    }
	else
	{
		$html .= "<p>You need to login to facebook in order to view your details</p>";
	}

	require_once("ui/templates/uea.php");
?>